import {
  post
} from '../../utils/request';

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    globalData: app.globalData,
    height: app.globalData.safeHeight - 50,
    activeKey: 0,
    list: [],
    heightList: [],
    leftId: 'left0',
    rightId: 'right0',
  },

  // 详情页面
  onDetail(e) {
    let {
      info
    } = e.currentTarget.dataset;
    // 商品
    if (info.type === 0) {
      wx.navigateTo({
        url: `/pages/goods/detail?id=${info.id}`,
      });
    }
    // 服务
    if (info.type === 1) {
      wx.navigateTo({
        url: `/pages/serve/detail?id=${info.id}`,
      });
    }
  },

  // 获取列表数据
  getList() {
    post(`/cate/list/${app.globalData.tenantCode}`)
      .then(resp => {
        if (resp.code === 0) {
          this.setData({
            list: resp.data.filter(d => d.items.length > 0)
          });
          setTimeout(() => {
            this.selectHeight();
          }, 0);
        }
      });
  },

  //计算右侧每个锚点的高距离顶部的高
  selectHeight() {
    let heightList = [];
    let h = 0;
    const query = wx.createSelectorQuery();
    query.selectAll('.category-body-list').boundingClientRect((react) => {
      react.forEach((res) => {
        h += res.height;
        heightList.push(h)
      })
      this.setData({
        heightList
      });
    }).exec();
  },

  changeScroll(e) {
    // 获取距离顶部的距离
    let scrollTop = e.detail.scrollTop;
    // 当前分类选中项,分类列表下标
    let {
      activeKey,
      heightList
    } = this.data;
    // 防止超出分类判断滚动距离是否超过当前分类距离顶部高度
    if (activeKey + 1 < heightList.length && scrollTop >= heightList[activeKey]) {
      this.setData({
        // 左侧分类选中项改变
        activeKey: activeKey + 1,
        // 左侧锚点对应位置
        leftId: `left${activeKey + 1}`
      })
    }
    if (activeKey - 1 >= 0 && scrollTop < heightList[activeKey - 1]) {
      this.setData({
        activeKey: activeKey - 1,
        leftId: `left${activeKey - 1}`
      })
    }
  },

  onChange(event) {
    let index = event.currentTarget.dataset.index;
    console.log(index);
    this.setData({
      activeKey: index,
      rightId: "right" + index,
      leftId: "left" + index,
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wx.setBackgroundColor({
      backgroundColor: "#ffffff"
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }

    this.getList();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

});